package com.decent.core.alarm.process.action;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.decent.common.bo.MessageBean;
import com.decent.common.entity.alarm.AlarmTemplate;
import com.decent.common.enums.CommonStatusEnum;
import com.decent.common.enums.alarm.AlarmTypeEnum;
import com.decent.core.alarm.annotation.AlarmTemplateField;
import com.decent.core.alarm.dao.AlarmCoreDao;
import com.decent.core.alarm.entity.bo.AlarmBO;
import com.decent.core.alarm.model.AlarmModel;
import com.decent.core.alarm.params.AlarmParams;
import com.decent.core.alarm.process.AlarmBusiness;
import com.decent.core.alarm.process.AlarmProcessContext;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 组建报警参数
 *
 * @author menghx
 * @date 2022-3-29
 */
@Slf4j
public class AlarmAssembleAction implements AlarmBusiness {
    @Resource
    private AlarmCoreDao alarmCoreDao;

    /**
     * 组建参数
     *
     * @param context 上下文
     */
    @Override
    public void process(AlarmProcessContext context) {
        AlarmModel sendModel = context.getProcessModel();
        AlarmParams params = sendModel.getParams();
        AlarmTypeEnum sendType = params.sendType();
        // 公司配置的模板信息
        AlarmTemplate template = alarmCoreDao.queryTemplate(sendType, CommonStatusEnum.NORMAL);
        if (template == null) {
            log.warn("发送报警,未配置模板无法发送报警context[{}]", JSONUtil.toJsonStr(context));
            context.setNeedBreak(true).setResponse(MessageBean.fail("未查询到模板无法发送报警!"));
            return;
        }
        String content = template.getTemplateContent();
        Class<?> clazz = params.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        Map<String, String> map = new HashMap<>(16);
        // 遍历找出模板参数与实际参数的对应
        for (Field field : declaredFields) {
            field.setAccessible(true);
            AlarmTemplateField annotation = field.getAnnotation(AlarmTemplateField.class);
            if (annotation != null && StrUtil.isNotBlank(annotation.value())) {
                try {
                    map.put(annotation.value(), (field.get(params)).toString());
                } catch (IllegalAccessException e) {
                    log.warn("发送报警,获取发送报警参数异常:反射获取字段异常[{}][{}][{}]", JSONUtil.toJsonStr(params), field.getName(), field.getType(), e);
                }
            }
        }
        // 将模板中的参数替换为实际发送的参数
        for (Map.Entry<String, String> temp : map.entrySet()) {
            content = content.replaceAll(temp.getKey(), temp.getValue());
        }
        sendModel.setAlarmBO(AlarmBO.builder()
                .url(template.getUrl())
                .content(content)
                .contentPrefix(template.getContentPrefix())
                .sendChannel(template.getSendChannel())
                .build());
    }


}
